package cn.com.woxitech.dev.controller.websocket;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import cn.com.woxitech.dev.common.RoomWebSocketSession;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.RoomService;

@Configuration
public class StompDisconnectEvent implements ApplicationListener<SessionDisconnectEvent> {
 
	@Autowired
	private RoomService roomService;

    @Autowired
    public SimpMessagingTemplate simp;
    
    public void onApplicationEvent(SessionDisconnectEvent event) {
    	Map<String, Object> mp = new HashMap<String,Object>();
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());

		String sessionid = sha.getSessionId();
		
		Map<String, Object> attributes = RoomWebSocketSession.getInstance().getAttributes(sessionid);
		if(attributes == null){
			return;
		}
        WmUser userInfo = (WmUser)attributes.get("userInfo");
		String useruuid = (String)attributes.get("useruuid");
		String roomuuid = (String)attributes.get("roomuuid");
		String type = "logout";

		if(userInfo == null){
			return;
		}
		mp.put("type", type);
		mp.put("headimgurl", userInfo.getWxHeadimgurl());
		mp.put("name", userInfo.getName());
		mp.put("time", System.currentTimeMillis());
		mp.put("useruuid", useruuid);
		mp.put("unionid", userInfo.getWxUnionid());
		mp.put("roomuuid", roomuuid);
		mp.put("sessionid", sessionid);
		
		this.roomService.removeUserOnline(useruuid, roomuuid);
		
		RoomWebSocketSession.getInstance().removeAttributes(sessionid);
		
		//saveHistory - 不保存logout信息
		
        simp.convertAndSend("/ws/room/"+roomuuid, mp);
        
    }
}